package com.rjs.serialization;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;


public class JSONSerializer implements ISerializer {
	
	private final static ObjectMapper mapper = new ObjectMapper();
	
	static {
		mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
		// 允许不带引号的字段名
		mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
		// 允许带单引号的字段名
		mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
		// 允许值里面有控制符（换行、换格等， ASCII小于32的值）
		mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
		// 反序列化的时候，碰到未知的属性不报错
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		// 序列化没有属性的类的时候不报错
		mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		
	}

	public byte[] serialize(Object obj) throws IOException {
		if (obj == null) {
			return new byte[0];
		}
		return mapper.writeValueAsBytes(obj);
	}

	public <T> T deserialize(byte[] buf, Class<T> clzz) throws IOException, ClassNotFoundException {
		String jsonStr = new String(buf);
		return mapper.readValue(jsonStr, clzz);
	}

}
